package com.fight.strive.sys.modules.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fight.strive.sys.modules.common.PageR;
import com.fight.strive.sys.modules.exception.StriveException;
import com.fight.strive.sys.modules.mybatis.MyBatisPlusUtils;
import com.fight.strive.sys.modules.rbac.dao.RbacResourceMapper;
import com.fight.strive.sys.modules.rbac.entity.RbacResourceEntity;
import com.fight.strive.sys.modules.rbac.service.RbacResourceService;
import com.fight.strive.sys.utils.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class RbacResourceServiceImpl
        extends ServiceImpl<RbacResourceMapper, RbacResourceEntity>
        implements RbacResourceService {

    @Override
    public void saveResource(RbacResourceEntity entity) {
        try {
            this.saveOrUpdate(entity);
        } catch (DuplicateKeyException e) {
            throw new StriveException("资源代码不能重复");
        }
    }

    @Override
    public IPage<RbacResourceEntity> listByPage(PageR<RbacResourceEntity> page) {
        QueryWrapper<RbacResourceEntity> queryWrapper = new QueryWrapper<>();
        MyBatisPlusUtils.buildRuleQuery(queryWrapper, page);
        if (ObjectUtils.notNull(page.getCondValue("roleId"))) {
            queryWrapper.exists("select id from t_sys_rbac_role_resource " +
                            "where resource_id = t_sys_rbac_resource.id and role_id = '{0}'",
                    page.getCondValue("roleId"));
        }
        queryWrapper.orderByAsc("seq");
        return this.page(page, queryWrapper);
    }

    @Override
    public List<RbacResourceEntity> listByRoleId(Long roleId) {
        QueryWrapper<RbacResourceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.exists("select id from t_sys_rbac_role_resource " +
                "where resource_id = t_sys_rbac_resource.id and role_id = '{0}'", roleId);
        queryWrapper.orderByAsc("seq");
        return this.list(queryWrapper);
    }

    @Override
    public Map<String, Map<String, Boolean>> getResourceCodeByRoleId(Long roleId) {
        return Collections.emptyMap();
    }

    @Override
    public void removeResource(RbacResourceEntity entity) {
        this.removeById(entity);
    }
}
